package cn.hashq.netpostclient.handler.proxy;

import cn.hashq.netpostclient.cache.ChannelCache;
import cn.hashq.netpostclient.dto.ProtoMsg;
import cn.hashq.netpostclient.handler.BaseHandler;
import cn.hashq.netpostclient.util.LogUtil;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@ChannelHandler.Sharable
public class PortConnectionBreakHandler extends BaseHandler {
    @Override
    public ProtoMsg.HeadType getHeadType() {
        return ProtoMsg.HeadType.PORT_CONNECT_BREAK;
    }

    @Override
    public void process(ChannelHandlerContext ctx, ProtoMsg.Message msg) {
        String sessionId = msg.getSessionId();
        Channel channel = ChannelCache.getInstance().getChannel(sessionId);
        if (Objects.nonNull(channel)) {
            log.info("服务端连接断开,本地连接断开,Session Id:{}", sessionId);
            channel.close().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    ChannelCache.getInstance().removeChannel(sessionId);
                    if (!future.isSuccess()) {
                        log.error("关闭本地连接失败,原因:{}", LogUtil.convertStackInfoToStr(future.cause()));
                    }
                }
            });
        }
    }
}
